<?php
if(isset($_GET['action'], $_GET['mod'], $_GET['id'])){
	$sMod = $_GET['mod'];
	$iId = $_GET['id'];

	require_once MODEL_DIR.'/CommentModel.php';
	switch($sMod){
		case 'devNotes':
			require_once MODEL_DIR.'/DevNotesModel.php';
			$oModInstance = new DevNotesModel();
			$aiasmModInfos = $oModInstance->getNotes("WHERE idNote = $iId");
			break;
		case 'project':
			require_once MODEL_DIR.'/ProjectModel.php';
			$oModInstance = new ProjectModel();
			$aiasmModInfos = $oModInstance->getProjects("WHERE idProject = $iId");
			break;
		case 'news':
			require_once MODEL_DIR.'/NewsModel.php';
			$oModInstance = new NewsModel();
			$aiasmModInfos = $oModInstance->getNews("WHERE idNews = $iId");
			break;
	}

	switch($_GET['action']){
		case 'view':
			$oCommentInstance = new CommentModel();
			$aiassCommentsList = $oCommentInstance->getComment("WHERE idTextModComment = $iId AND modComment = '$sMod'");
			require_once VIEW_DIR.'/comment.php';
			break;
		case 'add':
			require_once VIEW_DIR.'/formCommentAdd.php';
			break;
		case 'save':
			if(($_GET['mod'] === 'devNotes'
				OR $_GET['mod'] === 'project'
				OR $_GET['mod'] === 'news')
				AND !empty($_POST['authorComment'])
				AND !empty($_POST['textComment']))
			{
				$oCommentInstance = new CommentModel(array(
						'idTextMod' => $_GET['id'],
						'modComment' => $_GET['mod'],
						'authorComment' => $_POST['authorComment'],
						'emailAuthorComment' => $_POST['emailAuthor'],
						'websiteAuthorComment' => $_POST['websiteAuthor'],
						'textComment' => $_POST['textComment']
					));

				try{
					$oCommentInstance->isValidName();
					if(!empty($oCommentInstance->sEmailAuthorComment)){
						$oCommentInstance->isValidMail();
					}
					if(!empty($oCommentInstance->sWebsiteAuthorComment)){
						$oCommentInstance->isValidWebsite();
					}
				}catch (InvalidNameException $oException){
					$oException->addLog('InvalidNameException');
					$sMessage = $oException->getMessage();
					include_once VIEW_DIR.'/errors.php';
				}catch (InvalidMailException $oException){
					$oException->addLog('InvalidMailException');
					$sMessage = $oException->getMessage();
					include_once VIEW_DIR.'/errors.php';
				}catch (InvalidUrlException $oException){
					$oException->addLog('InvalidUrlException');
					$sMessage = $oException->getMessage();
					include_once VIEW_DIR.'/errors.php';
				}
				$oCommentInstance->addComment();
			}

			header('Location: index.php?page=comment&action=view&mod='.$sMod.'&id='.$iId);
			break;
	}
}